<?php
defined ( 'BASEPATH' ) or exit ( 'No direct script access allowed' );
/**
 * 购物车
 * @author chaituan@126.com
 */
class Car extends WechatCommon {

	function __construct(){
		parent::__construct();
		$this->load->library('fcart');
	}
	
	function index(){
		$items = $this->fcart->contents();
		$news = '';
		$ckarr = '';
		if($items){
			foreach ($items as $v){
				if(is_array($v)){
					$news[] = array('rid'=>$v['rowid'],'id'=>$v['id'],'qty'=>$v['qty'],'name'=>$v['name'],'price'=>$v['subtotal']*100,'options'=>$v['options']['options'],'thumb'=>$v['options']['thumb']);
					$ckarr[] = $v['rowid']; 
				}
			}
		}
		$data['ckarr'] = json_encode($ckarr);
		$data['items'] = $news;
		$this->load->view('mobile/mall/car',$data);
	}
	
	//添加购物车
	function add_car(){
		if(is_ajax_request()){
			$this->load->library('fcart');
			$data = Posts();
			$gid = $data['goodsId'];
			$price = $data['selectedSkuComb']['price']/100;
			$num = $data['selectedNum'];
			$this->load->model(array('admin/Goods_model'));
			$goods = $this->Goods_model->getItem(array('id'=>$gid),'sku_paths,thumb,names');
			if(!$goods)AjaxResult_error('商品不存在');
			$paths = json_decode($goods['sku_paths'],true);
			$options = '已选：'.implode(' + ',$paths[$data['selectedSkuComb']['id']]['values']);
			$shopid = 1;
			$items = array(
				'id' => $gid.str_replace(',', '', $data['selectedSkuComb']['id']),//生成特别id
				'qty' => $num,//数量
				'price' => $price,//单架
				'name' => $goods['names'],//产品名字
				'options' => array('options' => $options,'selPath' => $data['selectedSkuComb']['id'],'thumb' =>$goods['thumb'],'gid'=> $gid,'shopid'=>$shopid)
			);
			$this->fcart->insert(array($items));
			AjaxResult(1, '添加成功');
		}else{
			showmessage('错误请求','error');
		}
	}
	//编辑
	function edit_cart(){
		if(is_ajax_request()){
			$data = Posts('data');
			$items = $this->fcart->contents();
			$item = $items[$data['cid']];
			$item['qty'] = $data['num'];
			$r = $this->fcart->update(array($item));
			is_AjaxResult($r,"修改成功",'没有修改');
		}else{
			showmessage('错误请求','error');
		}
	}
	//删除
	function del(){
		if(is_ajax_request()){
			$data = Posts('data');
			foreach ($data as $v){
				$result = $this->fcart->remove($v);
			}
			is_AjaxResult($result,"删除成功","删除失败");
		}
	}
	
	function xh(){
		$this->fcart->destroy();
	}
}
